package com.agileai.miscdp.hotweb.ui.actions.treecontent;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.progress.IProgressService;

import com.agileai.miscdp.hotweb.domain.PageFormField;
import com.agileai.miscdp.hotweb.domain.treecontent.ContentTableInfo;
import com.agileai.miscdp.hotweb.domain.treecontent.TreeContentFuncModel;
import com.agileai.miscdp.hotweb.generator.treecontent.TACHandlerCfgGenerator;
import com.agileai.miscdp.hotweb.generator.treecontent.TACHandlerGenerator;
import com.agileai.miscdp.hotweb.generator.treecontent.TACJspPagGenerator;
import com.agileai.miscdp.hotweb.generator.treecontent.TACServiceCfgGenerator;
import com.agileai.miscdp.hotweb.generator.treecontent.TACServiceClassGenerator;
import com.agileai.miscdp.hotweb.generator.treecontent.TACServiceInterfaceGenerator;
import com.agileai.miscdp.hotweb.generator.treecontent.TACSqlMapCfgGenerator;
import com.agileai.miscdp.hotweb.generator.treecontent.TACSqlMapGenerator;
import com.agileai.miscdp.hotweb.ui.actions.BaseGenCodesAction;
import com.agileai.miscdp.hotweb.ui.dialogs.CodeGenConfigDialog;
import com.agileai.miscdp.hotweb.ui.editors.treecontent.TreeContentModelEditor;
import com.agileai.miscdp.hotweb.ui.editors.treecontent.TreeContentModelEditorContributor;
import com.agileai.miscdp.util.MiscdpUtil;
import com.agileai.domain.KeyNamePair;
import com.agileai.util.FileUtil;
import com.agileai.util.StringUtil;
/**
 * 代码生成动作
 */
public class TACGenCodesAction extends BaseGenCodesAction{
	private static final String GenOptionSection = "TreeContentModelEditor.GeneratorOption";
	
	public TACGenCodesAction() {
	}
	public void setContributor(TreeContentModelEditorContributor contributor) {
		this.contributor = contributor;
	}
	public void run() {
		TreeContentModelEditor modelEditor = (TreeContentModelEditor)this.getModelEditor();
		Shell shell = modelEditor.getSite().getShell();
		if (modelEditor.isDirty()){
    		String confirmTitle = MiscdpUtil.getIniReader().getValue("DialogInfomation","ConfirmTitle");
    		String confirmMsg = MiscdpUtil.getIniReader().getValue("DialogInfomation","IsSaveFirst");
    		boolean saveFirst = MessageDialog.openConfirm(shell, confirmTitle, confirmMsg);
    		if (saveFirst){
    			modelEditor.doSave(new NullProgressMonitor());
    		}else{
    			return;
    		}
    	}
		funcModel = modelEditor.buildFuncModel();
		
		CodeGenConfigDialog configDialog = new CodeGenConfigDialog(shell);
		List<KeyNamePair> inputGenList = new ArrayList<KeyNamePair>();
		inputGenList = MiscdpUtil.getIniReader().getList(GenOptionSection);
		configDialog.setInputGenList(inputGenList);
		configDialog.open();
		if (configDialog.getReturnCode() != Dialog.OK){
			return;
		}
		genertorMap = configDialog.getSelectedKeyNamePairs();
		
		IProgressService progressService = PlatformUI.getWorkbench().getProgressService();
		try {
	    	String projectName = funcModel.getProjectName();
	    	IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
			progressService.runInUI(progressService,this,project);
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	public void run(IProgressMonitor monitor) throws InvocationTargetException,
			InterruptedException {
		monitor.beginTask("init model values:", 1000);
		monitor.subTask("set model values....");
		monitor.worked(50);

    	String projectName = funcModel.getProjectName();
    	IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
    	File xmlFile = getXmlFile();
//    	this.funcModel = funcModel.buildFuncModel(xmlFile);

    	TreeContentFuncModel treeContentFuncModel = (TreeContentFuncModel)funcModel;
		String funcSubPkg = funcModel.getFuncSubPkg();
    	
		if (genertorMap.containsKey(GEN_OPTION_JSPPAGE)){
			monitor.subTask("generating jsp files....");
			monitor.worked(200);
			TACJspPagGenerator sMJspPagGenerator = new TACJspPagGenerator();
			sMJspPagGenerator.setXmlFile(xmlFile);

			String listJspName = project.getLocation().toString()+"/WebRoot/jsp/"+treeContentFuncModel.getListJspName();
			String template = treeContentFuncModel.getTemplate();
			sMJspPagGenerator.generateList(listJspName, template);
			
			String treePickJspName = project.getLocation().toString()+"/WebRoot/jsp/"+funcSubPkg+"/"+treeContentFuncModel.getTreePickJspName();
			sMJspPagGenerator.generateColumnPick(treePickJspName);
			
//        	String treeEditMode = treeContentFuncModel.getTreeEditMode();
        	boolean isManageTree = treeContentFuncModel.isManageTree();
        	if (isManageTree
//        			&& TreeContentFuncModel.TreeEditMode.Popup.toString().equals(treeEditMode)
        			){
    	    	String columnEditJspName = project.getLocation().toString()+"/WebRoot/jsp/"+funcSubPkg+"/"+treeContentFuncModel.getTreeEditJspName();
    			String uniqueFieldCode = funcModel.retrieveUniqueField(treeContentFuncModel.getTreeEditFormFields());
    			boolean checkUnique = !StringUtil.isNullOrEmpty(uniqueFieldCode);
    	    	sMJspPagGenerator.generateColumnEdit(columnEditJspName,checkUnique);
        	}
        	
        	List<ContentTableInfo> contentTableInfos = treeContentFuncModel.getContentTableInfoList();
        	for (int i=0;i < contentTableInfos.size();i++){
        		ContentTableInfo contentTableInfo = contentTableInfos.get(i);
        		String contentTabId = contentTableInfo.getTabId();
        		String contentTableName = contentTableInfo.getTableName();
        		String contentEditJspName = project.getLocation().toString()+"/WebRoot/jsp/"+funcSubPkg+"/"+treeContentFuncModel.getContentEditJspName(contentTableName);
        		List<PageFormField> pageFormFields = treeContentFuncModel.getContentEditFormFieldsMap().get(contentTabId);
        		String uniqueFieldCode = funcModel.retrieveUniqueField(pageFormFields);
    			boolean checkUnique = !StringUtil.isNullOrEmpty(uniqueFieldCode);
        		sMJspPagGenerator.generateContentEdit(contentEditJspName, i,checkUnique);
        	}
        	
		}		
		if (genertorMap.containsKey(GEN_OPTION_SQLMAP_DEFINE)){
			monitor.subTask("generating SqlMap files....");
			monitor.worked(300);
			TACSqlMapGenerator sMSqlMapGenerator = new TACSqlMapGenerator(projectName);
			sMSqlMapGenerator.setFuncModel(treeContentFuncModel);
			sMSqlMapGenerator.setProjectName(projectName);
	    	String abstSqlMapPath = project.getLocation().toString()+"/src/sqlmap";
	    	File tempFile = new File(abstSqlMapPath);
	    	if (!tempFile.exists()){
	    		tempFile.mkdirs();
	    	}
	    	String sqlMapFileName = treeContentFuncModel.getSqlNamespace();
	    	String sqlMapFile = abstSqlMapPath + "/" + sqlMapFileName+".xml";
	    	sMSqlMapGenerator.setSqlMapFile(sqlMapFile);
			sMSqlMapGenerator.generate();
		}
		if (genertorMap.containsKey(GEN_OPTION_SQLMAP_INDEX)){
			monitor.subTask("generating SqlMap config files....");
			monitor.worked(400);
			TACSqlMapCfgGenerator sMSqlMapCfgGenerator = new TACSqlMapCfgGenerator();
			String abstSqlMapCfgPath = project.getLocation().toString()+"/src/SqlMapConfig.xml";
			String sqlMapFileName = treeContentFuncModel.getSqlNamespace();
			sMSqlMapCfgGenerator.setSqlMapFileName(sqlMapFileName);
			sMSqlMapCfgGenerator.setConfigFile(abstSqlMapCfgPath);
			sMSqlMapCfgGenerator.generate();
		}
		
		if (genertorMap.containsKey(GEN_OPTION_SERVICE_CONFIG)){
			monitor.subTask("generating Service config files....");
			monitor.worked(500);
			TACServiceCfgGenerator sMServiceCfgGenerator = new TACServiceCfgGenerator();
			String abstServiceCfgPath = project.getLocation().toString()+"/src/ServiceContext.xml";
			sMServiceCfgGenerator.setConfigFile(abstServiceCfgPath);
			sMServiceCfgGenerator.setFuncModel(treeContentFuncModel);
			sMServiceCfgGenerator.setProjectName(projectName);
			sMServiceCfgGenerator.generate();	
		}
		
		if (genertorMap.containsKey(GEN_OPTION_HANDLER_CONFIG)){
			monitor.subTask("generating Handler config files....");
			monitor.worked(600);
			TACHandlerCfgGenerator sMHandlerCfgGenerator = new TACHandlerCfgGenerator();
			String abstHandlerCfgPath = project.getLocation().toString()+"/src/HandlerContext.xml";
			sMHandlerCfgGenerator.setConfigFile(abstHandlerCfgPath);
			sMHandlerCfgGenerator.setFuncModel(treeContentFuncModel);
			sMHandlerCfgGenerator.generate();	
		}
		
		String srcDir = project.getLocation().toString()+"/src";
		if (genertorMap.containsKey(GEN_OPTION_HANDLER_CLASS)){
			monitor.subTask("generating Handler java files....");
			monitor.worked(700);
			TACHandlerGenerator sMHandlerGenerator = new TACHandlerGenerator();
			sMHandlerGenerator.setSrcPath(srcDir);
			sMHandlerGenerator.setXmlFile(xmlFile);
			sMHandlerGenerator.setTreeContentFuncModel(treeContentFuncModel);
			sMHandlerGenerator.generate();			
		}
		
		if (genertorMap.containsKey(GEN_OPTION_SERVICE_IMPL)){
			monitor.subTask("generating Service Impl java files....");
			monitor.worked(800);
			
			TACServiceClassGenerator sMServiceClassGenerator = new TACServiceClassGenerator();
			String implClassName = funcModel.getImplClassName();
			File implJavaFile = FileUtil.createJavaFile(srcDir, implClassName);
			String implJavaFilePath = implJavaFile.getAbsolutePath();
			sMServiceClassGenerator.setJavaFile(implJavaFilePath);
			sMServiceClassGenerator.setXmlFile(xmlFile);
			sMServiceClassGenerator.generate();
			
			try {
				MiscdpUtil.getJavaFormater().format(implJavaFilePath, sMServiceClassGenerator.getCharencoding());	
			} catch (Exception e) {
				e.printStackTrace();
				throw new InvocationTargetException(e);
			}
		}

		if (genertorMap.containsKey(GEN_OPTION_SERVICE_INTERFACE)){
			monitor.subTask("generating Service Interface java files....");
			monitor.worked(900);
			
			TACServiceInterfaceGenerator sMServiceInterfaceGenerator = new TACServiceInterfaceGenerator();
			String interfaceClassName = funcModel.getInterfaceName();
			File interfaceJavaFile = FileUtil.createJavaFile(srcDir, interfaceClassName);
			
			String interfaceJavaFilePath = interfaceJavaFile.getAbsolutePath();
			sMServiceInterfaceGenerator.setJavaFile(interfaceJavaFilePath);
			sMServiceInterfaceGenerator.setXmlFile(xmlFile);
			sMServiceInterfaceGenerator.generate();
			try {
				MiscdpUtil.getJavaFormater().format(interfaceJavaFilePath, sMServiceInterfaceGenerator.getCharencoding());
			} catch (IOException e1) {
				e1.printStackTrace();
				throw new InvocationTargetException(e1);
			}
		}
		
		try {
			project.refreshLocal(IResource.DEPTH_INFINITE, null);
		} catch (CoreException e) {
			e.printStackTrace();
		}
	}
}
